const exec = require('child_process').exec;
const Koa = require('koa')
const Router = require('koa-router')
const router = new Router()
const multer = require('@koa/multer')
const path = require('path')
const serve = require('koa-static');
const app = new Koa();

//上传文件存放路径、及文件命名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, path.join(__dirname ,'proto-files'))
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname)
    }
})
//文件上传限制
// const limits = {
//     fields: 10,//非文件字段的数量
//     fileSize: 500 * 1024,//文件大小 单位 b
//     files: 1//文件数量
// }
// const upload = multer({storage,limits})
const upload = multer({storage})

router.post('/upload/file', upload.single('file'), async (ctx,next)=>{
  ctx.body = {
    code: 1,
    data: `http://192.168.0.9:3156/${ctx.file.filename}`
  }
})

router.get('/upload/hello', (ctx, next) => {
  const cmd = './protoc/bin/protoc -I ./proto-files --js_out=import_style=commonjs:./grpc --grpc-web_out=import_style=commonjs,mode=grpcweb:./grpc vcms.proto';
  exec(cmd, function(error, stdout, stderr) {
    console.log(error, stdout, stderr)
  });

  ctx.body = {
    data: 'hello world'
  }
})

const static = serve(path.join(__dirname, 'proto-files'));


app.use(static);
app.use(router.routes()).use(router.allowedMethods())
app.listen(3156)
